package com.wlz.jwt.config;

import com.wlz.jwt.filter.JWTAuthenticationEntryPoint;
import com.wlz.jwt.filter.JWTAuthenticationFilter;
import com.wlz.jwt.filter.JWTAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 *  security 整合 jwt
 *      测试：
 *          1. 使用 API Tester 工具 或者 postman 模拟 登陆请求， 会在请求头里返回 一个token
 *              POST  http://localhost:8080/login?username=wlz&password=123456
 *              返回 的token ： token: Bearer eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiW1JPTEVfYWRtaW4sIGFkbWluLCB1c2VyXSIsImV4cCI6MTYzMzQ1MDczOSwiaWF0IjoxNjMzNDUwNjUzLCJ1c2VybmFtZSI6IndseiJ9.gIF16MW5PUVDv0fx3zdmQGOCXcWd1-nK2yggK1RmBoo
 *          2. 使用 API Tester 工具 或者 postman 请求用户信息
 *              zai headers 中添加 Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiW1JPTEVfYWRtaW4sIGFkbWluLCB1c2VyXSIsImV4cCI6MTYzMzQ1MDczOSwiaWF0IjoxNjMzNDUwNjUzLCJ1c2VybmFtZSI6IndseiJ9.gIF16MW5PUVDv0fx3zdmQGOCXcWd1-nK2yggK1RmBoo
 *              POST  http://localhost:8080/user/getCurrentUser
 * @author wlz
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService myUserDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    /**
     * 表单登陆 配置
     * @param http
     * @throws Exception
     */
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.formLogin();  //表单登录
//        http.authorizeRequests()
//                .antMatchers("/user/**").hasRole("admin")
//                .anyRequest().authenticated() // 全部认证
//                .and().csrf().disable();
//    }

    /**
     *  前后端 分离 配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and().authorizeRequests()
                .antMatchers("/user/**").hasRole("admin")
                .anyRequest().permitAll()
                // 添加JWT登录拦截器
                .and().addFilter(new JWTAuthenticationFilter(authenticationManager()))
                // 添加JWT鉴权拦截器
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // 设置Session的创建策略为：Spring Security不创建HttpSession
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 匿名用户访问无权限资源时的异常处理
                .and().exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint())
                .and().csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 注册跨域配置
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

}
